<?php
include_once 'checkAdmin.php';
$carName = $_POST['carName'];
$carDesc = htmlspecialchars($_POST['carDesc']);
if($carName == '' || $carDesc == '' or $_FILES['carPIC']['name'] == ''){
    echo ("<script>alert('所有项目均为必填项。');history.back();</script>");
    exit;
}
/*print_r($_FILES['carPIC']['error']);*/
switch($_FILES['carPIC']['error']) {
    case 1:// 文件大小超出了服务器的空间大小
        echo ("<script>alert('上传文件太大了。');history.back();</script>");
        exit;
    case 2:// 要上传的文件大小超出浏览器限制
        echo ("<script>alert('上传文件太大了。');history.back();</script>");
        exit;
    case 3:// 文件仅部分被上传
        echo ("<script>alert('文件上传不完整。');history.back();</script>");
        exit;
    case 4:// 没有找到要上传的文件
        echo ("<script>alert('没有文件上传。');history.back();</script>");
        exit;
    case 5:// 服务器临时文件夹丢失
        echo ("<script>alert('服务器临时文件夹丢失。');history.back();</script>");
        exit;
    case 6:// 文件写入到临时文件夹出错
        echo ("<script>alert('文件写入到临时文件夹出错。');history.back();</script>");
        exit;
}
//程序如果能到这里，说明上传文件正常
//首先判断文件扩展名是否正确
$allowType = array('jpg','jpeg','png','gif');
$fileName = explode(".",$_FILES['carPIC']['name']);
$exd = strtolower(end($fileName)); //得到扩展名
if(!in_array($exd,$allowType)){
    echo ("<script>alert('文件类型出错。只能上传以下文件：".implode("，",$allowType)." ');history.back();</script>");
    exit;
}
//其次，判断文件大小，不超过1MB
if($_FILES['carPIC']['size'] > 1048576){
    echo ("<script>alert('文件尺寸不能超过1MB。');history.back();</script>");
    exit;
}
$newFileName = uniqid('',true).".$exd";
if(move_uploaded_file($_FILES['carPIC']['tmp_name'],'./img/'.$newFileName)){
    //说明文件上传成功
    //在carinfo中添加一条记录
    include "conn.php";
    $sql = "insert into carinfo (carName, carPIC, carDesc) VALUES ('$carName','$newFileName','$carDesc')";
    $result = mysqli_query($conn,$sql);
    if(mysqli_insert_id($conn)){
        echo ("<script>alert('添加车辆信息成功。');location.href='admin.php';</script>");
    }
    else{
        echo ("<script>alert('添加车辆信息失败。');history.back();</script>");
        exit;
    }
}
else{
    //说明文件上传失败
    echo ("<script>alert('添加车辆信息失败。');history.back();</script>");
    exit;
}

